<!--  -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model.lazy.trim="queryInfo.query" @keyup.enter.native="getUserList()" @change="getUserList()" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUserDialog = true"> 添加用户</el-button>
        </el-col>
      </el-row>
      <el-table border style="width: 100%" :data="userlist" v-loading="getLoading">
        <el-table-column type="index" label="#" align="center"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template v-slot="{row}">
            <el-switch v-model="row.mg_state" @change="switchChang(row)" :disabled="row.switchChangLoading"></el-switch>

          </template>

        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template v-slot="{row}">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="setUserDialogShow(row)" :loading="row.setLoadingBtn"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="delUser(row)" :loading="row.delLoading"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoleShow(row)" :loading="row.setRoleLoadingBtn"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[2, 4, 6, 8]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="queryInfo.total"></el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addUserDialog" width="50%" @close="addUserClosed" prop="addFormRef" :close-on-click-modal="false">
      <!-- 内容主体区域 -->
      <el-form :model="addUserForm" label-width="70px" @keyup.enter.native="addUser()" :rules="addFormRules" ref="addFormRef">
        <el-form-item label="用户名" prop="username"   >
          <el-input v-model.trim="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model.trim="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model.trim="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="addUser()" :loading="addLoading">确 定</el-button>
      </span>
    </el-dialog>

<!-- 修改用户的对话框 -->
    <el-dialog title="修改用户" :visible.sync="setUserDialog" width="50%" @close="setUserDialogClosed"  :close-on-click-modal="false">
      <el-form :model="editForm" @keyup.enter.native="setUser()" ref="setUser" label-width="70px" :rules="editFormRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model.trim="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model.trim="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="setUser()" :loading="setLoading">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialog" width="50%" @close="setRoleDialogClosed">
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择" value="1">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo" :loading="setRoleLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }

    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }
    return {
      userlist: [{}],
      queryInfo: {
        total: null,
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 4
      },

      getLoading: false, // 加载开关
      setRoleLoading: false,
      addLoading: false,
      setLoading: false,
      setRoleDialog: false, // 弹窗开关
      addUserDialog: false,
      setUserDialog: false,

      addUserForm: {},
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码的长度在6~15个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      userInfo: {

      },
      selectedRoleId: null,
      rolesList: {

      }
    }
  },

  created () { // 进入页面就开始执行
    this.getUserList()
  },

  components: {// 组件
  },

  computed: {// 计算属性是属性调用，而methods是函数调用
  },

  methods: { // 存储方法，处理复杂逻辑
    getUserList () {
      this.getLoading = true
      this.$http.get('users', { params: this.queryInfo }).then(res => {
        res = res.data
        if (res.meta.status !== 200) {
          return this.$message.error('获取用户列表失败！')
        }
        this.queryInfo.total = res.data.total
        this.userlist = res.data.users
      }).catch(err => {
        this.$message.error(err || '错误')
      }).finally(() => {
        this.getLoading = false
      })
    },

    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    addUserClosed () {
      this.$refs.addFormRef.resetFields()
    },
    setUserDialogClosed () {
      this.$refs.setUser.resetFields()
    },
    setRoleDialogClosed () {
      this.selectedRoleId = ''
      this.userInfo = {}
    },
    addUser () {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return
        this.addLoading = true
        this.$http.post('users', this.addUserForm).then(res => {
          res = res.data
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }
          this.$message.success(res.meta.msg)
          this.queryInfo.total += 1
          this.queryInfo.pagenum = Math.ceil((this.queryInfo.total) / this.queryInfo.pagesize)
          this.getUserList()
          this.addUserDialog = false
        }).catch(err => {
          this.$message.error(err || '错误')
        }).finally(() => {
          this.addLoading = false
        })
      })
    },
    delUser (row) {
      this.$set(row, 'delLoading', true)
      this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.$http.delete('users/' + row.id).then(res => {
          res = res.data

          if (res.meta.status !== 200) {
            return this.$message.error('删除用户失败！')
          }

          this.$message.success('删除用户成功！')

          // 删除页码最后一项自动翻页
          const totalPage = Math.ceil((this.queryInfo.total - 1) / this.queryInfo.pagesize) // 总页数
          this.queryInfo.pagenum = this.queryInfo.pagenum > totalPage ? totalPage : this.queryInfo.pagenum
          this.queryInfo.pagenum = this.queryInfo.pagenum < 1 ? 1 : this.queryInfo.pagenum
          this.getUserList()
          // total总数据量
          // pagesize当前每页显示多少条数据
          // pagenum当前的页码
        }).catch(err => {
          this.$message.error(err || '错误')
        }).finally(() => {
          this.$set(row, 'delLoading', false)
        })
      }).catch(() => {
        this.$set(row, 'delLoading', false)
      })
    },
    switchChang (row) {
      this.$set(row, 'switchChangLoading', true)
      console.log(row.id, row.mg_state)
      this.$http.put('users/' + row.id + '/state/' + row.mg_state).then(res => {
        res = res.data
        if (res.meta.status !== 200) {
          row.mg_state = !row.mg_state
          return this.$message.error('修改用户状态错误！')
        }
        this.$message.success('修改用户状态成功！')
      }).catch(err => {
        row.mg_state = !row.mg_state
        this.$message.error(err || '错误')
      }).finally(() => {
        this.$set(row, 'switchChangLoading', false)
      })
    },
    setUser () {
      this.$refs.setUser.validate(valid => {
        if (!valid) return
        this.setLoading = true
        this.setUserDialog = true
        this.$http.put('users/' + this.editForm.id, this.editForm).then(res => {
          res = res.data
          if (res.meta.status !== 200) {
            return this.$message.error('编辑用户信息错误！')
          }

          this.$message.success('编辑用户信息成功！')
          this.getUserList()
          this.setUserDialog = false
        }).catch(err => {
          this.$message.error(err || '错误')
        }).finally(() => {
          this.setLoading = false
        })
      })
    },
    setUserDialogShow (row) {
      this.$set(row, 'setLoadingBtn', true)
      this.$http.get('users/' + row.id).then(res => {
        res = res.data
        if (res.meta.status !== 200) {
          return this.$message.error('查询用户信息失败！')
        }
        setTimeout(() => {
          this.editForm = res.data
        }, 0)

        this.setUserDialog = true
      }).catch(err => {
        this.$message.error(err || '错误')
      }).finally(() => {
        this.$set(row, 'setLoadingBtn', false)
      })
    },
    saveRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$message.error('请选择要分配的角色！')
      }

      this.setRoleLoading = true
      this.$http.put('users/' + this.userInfo.id + '/role', { rid: this.selectedRoleId }).then(res => {
        res = res.data
        if (res.meta.status !== 200) {
          return this.$message.error('分配角色失败！')
        }
        this.$message.success('分配角色成功！')
        this.getUserList()
        this.setRoleDialog = false
      }).catch(err => {
        this.$message.error(err || '错误')
      }).finally(() => {
        this.setRoleLoading = false
      })
    },

    setRoleShow (row) {
      this.$set(row, 'setRoleLoadingBtn', true)
      this.$http.get('roles/').then(res => {
        res = res.data
        if (res.meta.status !== 200) {
          return this.$message.error('获取角色列表失败！')
        }
        this.userInfo = row
        this.rolesList = res.data
        this.setRoleDialog = true
      }).catch(err => {
        this.$message.error(err || '错误')
      }).finally(() => {
        this.$set(row, 'setRoleLoadingBtn', false)
      })
    }

  },

  props: []
}
</script>
<style lang='less' scoped>

</style>
